package com.zhang.backend.controller;

import com.zhang.backend.common.response.Result;
import com.zhang.backend.dto.LoginRequest;
import com.zhang.backend.dto.LoginResponse;
import com.zhang.backend.dto.RegisterRequest;
import com.zhang.backend.entity.User;
import com.zhang.backend.service.UserService;
import com.zhang.backend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * Handles user login.
     */
    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
        );
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = jwtUtil.generateToken(userDetails);
        return Result.success(new LoginResponse(token));
    }

    /**
     * Handles new user registration.
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody RegisterRequest registerRequest) {
        if (userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", registerRequest.getUsername())) != null) {
            return Result.failure(400, "Error: Username is already taken!");
        }
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
        user.setEmail(registerRequest.getEmail());
        userService.save(user);
        return Result.success("User registered successfully!");
    }
}